package leetcode;

import java.util.Arrays;

/**
 * @创建人 MBY381
 * @创建时间 2022/5/11 18:35
 * @描述 暂无
 */
public class Solution34 {
    public static void main(String[] args) {
        int[] nums = new int[]{5, 7, 7, 8, 8, 10};
        System.out.println(Arrays.toString(searchRange(nums, 8)));
    }


    /**
     * 不包含目标值时有错
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] searchRange(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int[] ans = new int[]{-1, -1};
        if (nums.length == 1 && target == nums[0]) {
            return new int[]{0, 0};
        }
        while (left < right) {
            int mid = (left + right) / 2;
            if (target < nums[mid]) {
                right = mid - 1;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                left = mid;
                right = mid;
                while (left >= 0) {
                    boolean tag = true;
                    if (nums[left] == target) {
                        tag = false;
                        left--;
                    }
                    if (tag) {
                        break;
                    }
                }
                while (right < nums.length) {
                    boolean tag = true;
                    if (nums[right] == target) {
                        tag = false;
                        right++;
                    }
                    if (tag) {
                        break;
                    }
                }
                if (left != mid) {
                    ans[0] = left + 1;
                }
                if (right != mid) {
                    ans[1] = right - 1;
                }
                break;
            }
        }
        return ans;
    }


    public int[] searchRange1(int[] nums, int target) {
        int leftIdx = binarySearch(nums, target, true);
        int rightIdx = binarySearch(nums, target, false) - 1;
        if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
            return new int[]{leftIdx, rightIdx};
        }
        return new int[]{-1, -1};
    }

    public int binarySearch(int[] nums, int target, boolean lower) {
        int left = 0, right = nums.length - 1, ans = nums.length;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target || (lower && nums[mid] >= target)) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}
